package com.cloud.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * AES加密解密 卫健委出生一件事对接
 */
public class AESUtil {
    private static final Logger log = LoggerFactory.getLogger(AESUtil.class);

    public static void main(String[] args) {
        String key = "9703576e20374eea";
//        String str = "idNo=330226199302094973&noncestr=Wm3WZYTPz0wzccnW&timestamp=1484295549000";
//        String encodeString = encodeAES(str,"d8aab995-0329-4f");
//        System.out.println(encodeString);
//        System.out.println(decodeAES(encodeString,"d8aab995-0329-4f"));
        String str = "SS8zUE5wc0ZHWlJ1TnVrdmhIZlNkelFGeCtQVHNhT2RnRnE1Vlp4M2dMNVhuNXVaeW5GVTA2aXE1UFB4WXNsTHUrUkthbzd2M0ZrTApxYXZrenN5ME5ROFgzemh0dVhaTGxKSk9TMmZ5amxacURZbFVJd0NqbUV0c3didmFHNHpLQ3AxaTZFNDQ0UXlrazhuQ1ZSMjFSQ2pjCllEcUpabjZ6U0tZeTg3S2RpZUUydHZMNUREUWV4Zjd5ek12TUpJRmYyeUUzUmIzOE55REltL1ppWFNMTmhtQ2orYzBIWWhvM3pqODIKVkRSRHVDZTBaM0FidEx6VmNvNVNJQlVhQmpzLw==";

        try {
            String tempPushMsg = AESUtil.decodeAESBase64(new String(Base64.decodeBase64(str), "UTF-8"), key);
            System.out.println(tempPushMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * AES加密
     * @author yekaiqiang
     * @param: [var,keyString]
     * @return String
     * @date 2017/1/11 18:41
     */
    public static String encodeAES(String content,String keyString){
        byte[] result = new byte[0];
        try {
            // 获取密钥
            byte[] keyBytes = keyString.getBytes();
            // KEY转换
            Key key = new SecretKeySpec(keyBytes, "AES");
            // 加密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            result = cipher.doFinal(content.getBytes());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Hex.encodeHexString(result);
    }

    /**
     * AES解密
     * @author yekaiqiang
     * @param: [var,keyString]
     * @return String
     * @date 2017/1/11 18:45
     */
    public static String decodeAES(String var,String keyString){
        byte[] result = new byte[0];
        try {
            result = Hex.decodeHex(var.toCharArray());
            // 获取密钥
            byte[] keyBytes = keyString.getBytes();
            // KEY转换
            Key key = new SecretKeySpec(keyBytes, "AES");
            // 解密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            result = cipher.doFinal(result);
        } catch (Exception e){
            log.error(e.getMessage());
        }
        return new String(result);
    }

    public static boolean verifyText(String text,String keyString,String signature){
        String encodeResult = encodeAES(text,keyString);
        log.info("加密后的签名："+encodeResult);
        log.info("原签名："+signature);
        if(encodeResult.equals(signature)){
            log.info("签名验证成功");
            return true;
        }
        log.info("签名验证失败");
        return false;
    }

    /**
     * AES加密，并将结果base64编码
     * @param dataStr
     * @param keyString
     * @return
     */
    public static String encodeAESBase64(String dataStr,String keyString) throws Exception{
        byte[] result = new byte[0];

        // 获取密钥
        byte[] keyBytes = keyString.getBytes();
        // KEY转换
        Key key = new SecretKeySpec(keyBytes, "AES");
        // 加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        result = cipher.doFinal(dataStr.getBytes("utf-8"));

        return new BASE64Encoder().encode(result);
    }

    /**
     * AES解密，并将数据串base64解码
     * @param dataStr
     * @param keyString
     * @return
     */
    public static String decodeAESBase64(String dataStr,String keyString) throws Exception{
        byte[] result = new byte[0];

        result = new BASE64Decoder().decodeBuffer(dataStr);
        // 获取密钥
        byte[] keyBytes = keyString.getBytes();
        // KEY转换
        Key key = new SecretKeySpec(keyBytes, "AES");
        // 解密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        result = cipher.doFinal(result);

        return new String(result);
    }
}
